package cn.edu.zjgsu.ito.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Record;

import cn.edu.zjgsu.ito.service.AdminExportStuService;
import cn.edu.zjgsu.ito.service.ServiceFactory;


public class AdminExportStuController extends Controller {
	
	private AdminExportStuService adminExportStuService =ServiceFactory.createAdminExportStuService();
	private List<Record> records;
	private Record record;
	public static final DateFormat formatter=new SimpleDateFormat("yyyyMMddHHmmss");
	
	
	/**
	  * 课程学生名单导出
	  * 杨昆鹏
	  * 
	  * */
	public void exportCouStuExcel(){
		String stuName = "";
		OutputStream out = null;
		String uuid=getPara("uuid");
		
		System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		Date date = new Date();
		String time=formatter.format(date);

		System.out.println(time);
		
		String filedir=PathKit.getWebRootPath();
		filedir=filedir+"\\WEB-INF\\download\\";
		System.out.println("------1------");
        deleteFile(new File(filedir));//清空缓存区
        System.out.println("------2------");
		List<Record> teaTime = adminExportStuService.test(uuid);
		records=adminExportStuService.CourseStu(uuid);
		
		System.out.println(teaTime);
		System.out.println(records);
		String term = teaTime.get(0).getStr("termValue").replace("/", "-");
		String courseName = teaTime.get(0).getStr("courseName");
		String tName = teaTime.get(0).getStr("tName").replace(",","");
		
		System.out.println("------3------");
		String temp = term + courseName + tName + time +".xls";
		stuName= stuName + temp;
		String outpath = filedir+stuName;
		try {
			out = new FileOutputStream(outpath);
			System.out.println(filedir+stuName);
			adminExportStuService.exportCouStuExcel(teaTime, records, out);
			System.out.println("------4-------");
			System.out.println("------5-------");
			String path = filedir + stuName;
			renderFile(new File(path));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	 		
		
	}
	
	public void deleteFile(File oldPath) {
        if (oldPath.isDirectory()) {
         File[] files = oldPath.listFiles();
         for (File file : files) {
           deleteFile(file);
         }
        }else{
          oldPath.delete();
        }
      }

}
